/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.emex.app.stuff.gui;

import com.emex.app.shared.data.OrderPosition;
import com.emex.app.shared.data.Provider;
import com.emex.app.shared.data.enums.OrderPositionStatus;
import com.emex.app.stuff.gui.model.OrderPositionTableModel;
import com.emex.app.stuff.gui.model.ProviderComboBoxModel;
import com.emex.app.stuff.provider.ProviderDataProvider;
import com.emex.app.stuff.utils.StringUtilities;
import com.emex.app.stuff.utils.UIUtils;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author Sergey Karavaev
 */
public class OrderPositionDialog extends javax.swing.JDialog {

    private OrderPosition orderPosition;

    private OrderPositionTableModel tableModelToUpdate;

    /**
     * Creates new form OrderPositionDialog
     */
    public OrderPositionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        customInit();
    }

    private void customInit() {
        statusComboBox.setModel(new DefaultComboBoxModel(OrderPositionStatus.values()));
        providerComboBox.setModel(new ProviderComboBoxModel());
    }

    public void setOrderPosition(OrderPosition orderPosition) {
        this.orderPosition = orderPosition;

        if (null != orderPosition) {
            nameField.setText(orderPosition.getName());
            amountSpinner.setValue(orderPosition.getAmount());
            priceField.setText(orderPosition.getPrice().toString());
            purPriceField.setText(orderPosition.getPurPrice().toString());
            statusComboBox.setSelectedItem(OrderPositionStatus.valueOf(orderPosition.getStatus()));
            Provider prov = ProviderDataProvider.getInstance().selectProviderByPrimaryKey(orderPosition.getProviderId());
            if (null != prov && providerComboBox.getItemCount() > 0) {
                for (int i = 0; i < providerComboBox.getItemCount(); ++i) {
                    Provider p = (Provider) providerComboBox.getItemAt(i);
                    if (p.getName().equals(prov.getName())) {
                        providerComboBox.setSelectedIndex(i);
                        break;
                    }
                }
            }
        }
    }

    public void setTableModelToUpdate(OrderPositionTableModel tableModelToUpdate) {
        this.tableModelToUpdate = tableModelToUpdate;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        amountSpinner = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        priceField = new javax.swing.JTextField();
        purPriceLabel = new javax.swing.JLabel();
        purPriceField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        statusComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        providerComboBox = new javax.swing.JComboBox();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.title")); // NOI18N
        setResizable(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.jLabel1.text")); // NOI18N

        nameField.setText(org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.nameField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.jLabel2.text")); // NOI18N

        amountSpinner.setValue(Integer.valueOf(1)
        );

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.jLabel3.text")); // NOI18N

        priceField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        priceField.setText(org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.priceField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(purPriceLabel, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.purPriceLabel.text")); // NOI18N

        purPriceField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        purPriceField.setText(org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.purPriceField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.jLabel4.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.jLabel5.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.saveButton.text")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(OrderPositionDialog.class, "OrderPositionDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(purPriceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(amountSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(priceField, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(purPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(statusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(providerComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(amountSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(priceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(purPriceLabel)
                    .addComponent(purPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(statusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(providerComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        boolean operationCreate = false;

        if (orderPosition == null) {
            orderPosition = new OrderPosition();
            operationCreate = true;
        }

        if (nameField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Заполните название позиции");
            return;
        }
        Integer amount = (Integer) amountSpinner.getValue();
        if (amount == 0) {
            UIUtils.showErrorMessage("Количество должно быть больше 0");
            return;
        }
        if (priceField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Заполните цену позиции");
            return;
        }
        if (purPriceField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Заполните закупочную цену");
            return;
        }
        if (null == statusComboBox.getSelectedItem()) {
            UIUtils.showErrorMessage("Укажите статус позиции");
            return;
        }

        orderPosition.setName(StringUtilities.formatStringFromSpecialCharacters(nameField.getText()));
        orderPosition.setAmount(amount);
        String price = priceField.getText();
        orderPosition.setPrice(Double.valueOf(price.replaceAll(",", ".")));
        String purPrice = purPriceField.getText();
        orderPosition.setPurPrice(Double.valueOf(purPrice.replaceAll(",", ".")));
        OrderPositionStatus orderPositionStatus = (OrderPositionStatus) statusComboBox.getItemAt(statusComboBox.getSelectedIndex());
        orderPosition.setStatus(orderPositionStatus.ordinal());
        Provider prov = (Provider) providerComboBox.getSelectedItem();
        if (null != prov) {
            orderPosition.setProviderId(prov.getId());
        }

        if (operationCreate) {
            tableModelToUpdate.dataAdded(orderPosition);
        } else {
            tableModelToUpdate.dataUpdated();
        }

        this.setVisible(false);
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSpinner amountSpinner;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField nameField;
    private javax.swing.JTextField priceField;
    private javax.swing.JComboBox providerComboBox;
    private javax.swing.JTextField purPriceField;
    private javax.swing.JLabel purPriceLabel;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox statusComboBox;
    // End of variables declaration//GEN-END:variables
}
